package com.meida.module.bus.provider.util;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.constants.CommonConstants;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.awt.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * @Description: 工具类
 * @ClassName ToolsUtil
 * @date: 2022.06.23 12:46
 * @Author: ldd
 */
@Log4j2
public class ToolsUtil {
    /**
     * description:  error_code为0仅代表端口通讯成功
     * date: 2022年-06月-23日 13:13
     * author: ldd
     */
    static String errorCode = "error_code";

    /**
     * description:  业务逻辑码isok值当isok为true为匹配 false为不匹配
     * date: 2022年-06月-23日 13:13
     * author: ldd
     */
    static String isOk = "isok";

    public static String calcAuthorization(String source, String secretId, String secretKey, String datetime)
            throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        String signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
        Mac mac = Mac.getInstance("HmacSHA1");
        Key sKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm());
        mac.init(sKey);
        byte[] hash = mac.doFinal(signStr.getBytes("UTF-8"));
        String sig = Base64.encodeBase64String(hash);

        String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"" + sig + "\"";
        return auth;
    }

    public static String urlencode(Map<?, ?> map) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(String.format("%s=%s",
                    URLEncoder.encode(entry.getKey().toString(), "UTF-8"),
                    URLEncoder.encode(entry.getValue().toString(), "UTF-8")
            ));
        }
        return sb.toString();
    }

    @SneakyThrows
    public static boolean verifyIdcard(String secretId, String secretKey, String realName, String cardNo, String url) {
        boolean ok = false;
        String source = "market";
        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String datetime = sdf.format(cd.getTime());
        // 签名
        String auth = calcAuthorization(source, secretId, secretKey, datetime);
        // 请求方法
        String method = "POST";
        // 请求头
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("X-Source", source);
        headers.put("X-Date", datetime);
        headers.put("Authorization", auth);

        // 查询参数
        Map<String, String> queryParams = new HashMap<String, String>();

        // body参数
        Map<String, String> bodyParams = new HashMap<String, String>();
        bodyParams.put("cardNo", cardNo);
        bodyParams.put("realName", realName);
        // url参数拼接
        if (!queryParams.isEmpty()) {
            url += "?" + urlencode(queryParams);
        }

        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setRequestMethod(method);

            // request headers
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }

            // request body
            Map<String, Boolean> methods = new HashMap<>();
            methods.put("POST", true);
            methods.put("PUT", true);
            methods.put("PATCH", true);
            Boolean hasBody = methods.get(method);
            if (hasBody != null) {
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                conn.setDoOutput(true);
                DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                out.writeBytes(urlencode(bodyParams));
                out.flush();
                out.close();
            }

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            String result = "";
            while ((line = in.readLine()) != null) {
                result += line;
            }
            JSONObject object = JSON.parseObject(result);
            if (CommonConstants.DISABLED_STR.equals(object.getString(errorCode))) {
                JSONObject bus = object.getJSONObject("result");
                ok = bus.getBoolean(isOk);
            }
        } catch (Exception e) {
            log.error(e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            return ok;
        }

    }


    public static void addWatermark(String url, String remark, String outPath, String fileName) {
        try {
            QrCodeUtil.generate(url, 280, 280, FileUtil.file(outPath + "qrcode.jpg"));

            ImgUtil.pressImage(
                    FileUtil.file(outPath + "share.jpg"),
                    FileUtil.file(outPath + "tmp.jpg"),
                    ImgUtil.read(FileUtil.file(outPath + "qrcode.jpg")),
                    //水印图片
                    5,
                    //x坐标修正值。 默认在中间，偏移量相对于中间偏移
                    240,
                    //y坐标修正值。 默认在中间，偏移量相对于中间偏移
                    0.8f
                    //透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
            );

            ImgUtil.pressText(
                    FileUtil.file(outPath + "tmp.jpg"),
                    FileUtil.file(outPath + fileName),
                    remark, Color.BLACK,
                    new Font("仿宋", Font.BOLD, 24),
                    //dynamicFont,
                    0,
                    400,
                    0.8f
            );
        } catch (Exception e) {
            log.error(e);
        }
    }

    public static void sendMsg(String secretId, String secretKey, String mobile, String templateId, String tag) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        String source = "market";

        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String datetime = sdf.format(cd.getTime());
        // 签名
        String auth = calcAuthorization(source, secretId, secretKey, datetime);
        // 请求方法
        String method = "POST";
        // 请求头
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("X-Source", source);
        headers.put("X-Date", datetime);
        headers.put("Authorization", auth);

        // 查询参数
        Map<String, String> queryParams = new HashMap<String, String>();

        // body参数
        Map<String, String> bodyParams = new HashMap<String, String>();
        bodyParams.put("mobile", mobile);
        bodyParams.put("tag", tag);
        bodyParams.put("templateId", templateId);
        // url参数拼接
        String url = "https://service-5ipqbocr-1308811306.sh.apigw.tencentcs.com/release/sms/send";
        if (!queryParams.isEmpty()) {
            url += "?" + urlencode(queryParams);
        }

        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setRequestMethod(method);

            // request headers
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }

            // request body
            Map<String, Boolean> methods = new HashMap<>();
            methods.put("POST", true);
            methods.put("PUT", true);
            methods.put("PATCH", true);
            Boolean hasBody = methods.get(method);
            if (hasBody != null) {
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                conn.setDoOutput(true);
                DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                out.writeBytes(urlencode(bodyParams));
                out.flush();
                out.close();
            }

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            String result = "";
            while ((line = in.readLine()) != null) {
                result += line;
            }

            System.out.println(result);
        } catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    public static void sendMsg(String mobile, String code) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        String url = "https://dx.ipyy.net/smsJson.aspx";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("action", "send");
        paramMap.put("userid", "69691");
        paramMap.put("account", "ZZ00983");
        paramMap.put("password", SecureUtil.md5("chpnd5e7").toUpperCase());
        paramMap.put("mobile", mobile);
        paramMap.put("content", "【再少点】您正在登录验证，验证码：" + code + "，切勿将验证码泄露于他人。");
        String post = HttpUtil.post(url, paramMap);
        System.out.println(post);
    }

    @SneakyThrows
    public static void main(String[] args) {


        String filePath = "/data/file/2022/07/04/747c42ed1b6449cb94ca343737dae904.jpg";
        Long fileId = 1543846225350094849L;
        if (FlymeUtils.isNotEmpty(filePath)) {
            filePath = filePath.substring(0, filePath.indexOf(fileId.toString()) + 20);
        }
        System.out.println(filePath);
      /*  String url="https://dx.ipyy.net/smsJson.aspx";

        Map<String, Object> paramMap=new HashMap<>();
        paramMap.put("action","send");
        paramMap.put("userid","69691");
        paramMap.put("account","ZZ00983");
        paramMap.put("password", SecureUtil.md5("chpnd5e7").toUpperCase());
        paramMap.put("mobile","15516193580");
        paramMap.put("content","【再少点】您正在登录验证，验证码：12345，切勿将验证码泄露于他人。");
        //String s = JSON.toJSONString(paramMap);
        //System.out.println(s);
        String post = HttpUtil.post(url,paramMap );
        System.out.println(post);*/


       /* String url="https://dx.ipyy.net/ensms.ashx";

        cn.hutool.json.JSONObject obj = JSONUtil.createObj();
        obj.set("UserName",  "ZZ00983");
        obj.set("Stamp", DateUtil.format(new Date(),"MMddHHmmss"));
        obj.set("Secret",   SecureUtil.md5("chpnd5e7").toUpperCase());
        obj.set("Moblie","15516193580");
        obj.set("Text","【再少点】您正在登录验证，验证码：12345，切勿将验证码泄露于他人。");
        String s = obj.toString();

        Key convertSecretKey =EncryUtils.generateSecret("chpnd5e7");
        String enStr =EncryUtils.encodeString(convertSecretKey, s);


        Map<String, Object> paramMap=new HashMap<>();
         paramMap.put("UserId","69691");
        paramMap.put("Text64",URLEncoder.encode(enStr, "UTF-8"));
        //String s = JSON.toJSONString(paramMap);
        //System.out.println(s);
        String post = HttpUtil.post(url,paramMap );
        System.out.println(post);*/
        //addWatermark("https://hutool.cn/", "邀请码：98W9B", "/Users/mhsdong/Desktop/yycx/", "share1.jpg");


        //BigDecimal temBonus = BigDecimal.valueOf(0);
        //temBonus = (BigDecimal.valueOf(450).subtract(BigDecimal.valueOf(135)).subtract(BigDecimal.valueOf(31.5))).multiply(BigDecimal.valueOf(0.3));
        //System.out.println(temBonus);
        //
        //BigDecimal divideTemBonus = temBonus.divide(BigDecimal.valueOf(99));
        //System.out.println(divideTemBonus);
        //
        //try {
        //    sendMsg("AKID5NR44HKvNkkArY4k8O4AR6HyAqNgKME5uXbY", "goOqYJ1xg3FdsV5O1H458rkAvW6166wRLQT3rm", "15516193580", "", "");
        //} catch (NoSuchAlgorithmException e) {
        //    e.printStackTrace();
        //} catch (UnsupportedEncodingException e) {
        //    e.printStackTrace();
        //} catch (InvalidKeyException e) {
        //    e.printStackTrace();
        //}
    }
}
